import {defineComponent, ref, computed,} from "vue"
import {NModal, NButton, NCard, NIcon, NGi, NInput, NFormItem, NSpace, NCheckbox, NCheckboxGroup,NResult,} from "naive-ui"
import {CloseOutlined, FullscreenOutlined} from "@vicons/antd"
import useEditModel from "@/hooks/editModel"
import Flexform, {flexformitem, meiyongfunc,} from "@/components/flexform/index"
import {SearchOutlined, PlusOutlined,} from "@vicons/antd"
import {ViewFilled, Edit, Delete, ResetAlt,} from "@vicons/carbon"
import useHttpMessage from "@/hooks/oftenattr";

export default defineComponent({
    name: "editModel",
    props: {
        close: {
            type: Function,
            default: null,
        },
    },
    setup({close}, {expose, emit}) {
        const errorText = ref("")
        const resetfunc = () => {
            errorText.value = ""
        }
        const {http, message} = useHttpMessage()
        const {
            showModel,
            handleInit,
            handleClose,
            handleReset,
            formValue,
            formRef,
            title,
            editType,
            resultText,
            loading,
            getSuccess,
            getFaild,
            handleReturn,
            result,
        } = useEditModel(null, resetfunc, "", close)
        expose({handleInit, handleClose, handleReset, formValue})
        // 点击增加选项
        const addoption = () => {
            // 必须先选择题型
            if (!formValue.value.testType) {
                message.error("请先选择题型")
                return
            }
            // 如果不是数组，先变成数组
            if (!Array.isArray(formValue.value.options)) {
                formValue.value.options = []
            }
            // 如果是判断题，最多两个下选项
            if (formValue.value.testType === "1" && formValue.value.options.length >= 2) {
                message.error("判断题最多两个选项")
                return
            }
            // 最多不要超过10个选项
            if (formValue.value.options.length >= 10) {
                message.error("最多10个选项")
                return
            }
            // 没问题了，添加选项
            formValue.value.options.push({
                content: "",
                checked: false,
            })
        }
        // 点击删除选项
        const deleteItem = (index: number) => {
            formValue.value.options.splice(index, 1)
        }
        // 修改选项的选中状态
        const changCheck = (xuhao: number) => {
            if (formValue.value.testType !== "2") {
                formValue.value.options.forEach((item: any, index: number) => {
                    if (xuhao !== index) {
                        item.checked = false;
                    }
                })
            }
        }
        // 点击保存
        const handleSave = () => {
            errorText.value = ""
            if (formValue.value["testType"] === "1") {
                // 判断题需要两个选项
                if (formValue.value.options.length !== 2) {
                    errorText.value = "判断题必须有两个选项"
                    return false
                }
                const daan = formValue.value.options.filter((item: any) => item.checked)
                if (daan.length !== 1) {
                    errorText.value = "判断题有且只有一个答案"
                    return false
                }
            } else if (formValue.value["testType"] === "0") {
                // 单选题不能超过10个选项，且只有一个答案
                if (formValue.value.options.length >= 10) {
                    errorText.value = "单选题必须有两个选项"
                    return false
                } else if (formValue.value.options.length <= 2) {
                    errorText.value = "单选题至少有两个选项"
                    return false
                }
                const daan = formValue.value.options.filter((item: any) => item.checked)
                if (daan.length !== 1) {
                    errorText.value = "单选题有且只有一个答案"
                    return false
                }
            } else if (formValue.value["testType"] === "2") {
                // 多选题不能超过10个选项，必须有答案
                if (formValue.value.options.length >= 10) {
                    errorText.value = "多选题必须有两个选项"
                    return false
                } else if (formValue.value.options.length <= 2) {
                    errorText.value = "多选题至少有两个选项"
                    return false
                }
                const daan = formValue.value.options.filter((item: any) => item.checked)
                if (daan.length === 0) {
                    errorText.value = "多选题至少有一个答案"
                    return false
                }
            } else {
                errorText.value = "不会出现的错误"
                return false
            }

            formRef.value?.jiaoyan(() => {
                http.testquestionadd(formValue.value, loading).then((res: any) => {
                    if (res.data.success) {
                        getSuccess(res.data.msg || "创建成功")
                        setTimeout(() => {
                            handleClose()
                        }, 500)
                    } else {
                        getFaild(res.data.msg || "创建失败")
                    }
                }).catch(err => {
                    getFaild(err.message || "系统错误")
                })
            })
        }

        // 自定义属性
        const formList = ref([
            {
                show: true,
                span: 24,
                label: "考题类型",
                key: "testType",
                default: "",
                type: "select",
                options: [
                    {label: "单选题", value: "0"},
                    {label: "判断题", value: "1"},
                    {label: "多选题", value: "2"},
                ],
                placeholder: "请选择考题类型",
                rules: [
                    {required: true, message: "请选择考题类型", trigger: "change"}
                ],
            },
            {
                show: true,
                span: 24,
                label: "考题内容",
                key: "content",
                default: "",
                type: "textarea",
                placeholder: "请输入考题内容",
                rules: [
                    {required: true, message: "请输入考题内容", trigger: "change"}
                ],
            },
            {
                show: true,
                type: "slot",
                slot: () => <div class="w-full my-3 flex justify-end ">
                    <NButton type={"info"} v-slots={{
                        icon: () => <NIcon size={16}>
                            <PlusOutlined/>
                        </NIcon>
                    }} onClick={addoption}>添加选项</NButton>
                </div>
            },
            {
                show: true,
                span: 24,
                label: "考题选项",
                type: "slot",
                slot: () => <div class="w-full">
                    {Array.isArray(formValue.value.options) ? formValue.value.options.map((item: any, index: number) => {
                        return <NGi span={24} class="flex">
                            <NFormItem label={"选项" + (index + 1) + "："} path={"options." + index + ".content"}
                                       rule={[{required: true, message: "请输入选项内容", trigger: "change",}]}>
                                <NSpace>
                                    <NInput v-model={[item["content"], "value"]} onKeydown={meiyongfunc}
                                            placeholder={"请输入"}
                                            clearable={true}
                                            size={"small"}>
                                    </NInput>
                                    <NCheckbox v-model={[item["checked"], "checked"]} label={"是否是答案"}
                                               onUpdateChecked={() => changCheck(index)}/>
                                    <NButton type={"error"} size={"small"} v-slots={{
                                        icon: () => <NIcon size={16}>
                                            <Delete/>
                                        </NIcon>
                                    }} onClick={() => deleteItem(index)}/>
                                </NSpace>
                            </NFormItem>
                        </NGi>
                    }) : null}
                </div>
            },
            {
                show: true,
                span: 24,
                label: "备注",
                key: "desc",
                default: "",
                type: "textarea",
                placeholder: "请输入考题内容",
            },
        ])
        const actionSlot = () => (<div class="flex justify-end items-center my-1">
            <NButton onClick={handleClose}>关闭</NButton>
            {(result.value === "" && editType.value === "add") ? <NButton class="ml-10px" type={"info"}
                                                                          onClick={handleSave}>创建</NButton> : (result.value === "" && editType.value === "edit") ?
                <NButton class="ml-10px" type={"info"} onClick={handleSave}>修改</NButton> : null}
            {result.value === "failed" ?
                <NButton class="ml-10px" type={"primary"} onClick={handleReturn}>返回</NButton> : null}
        </div>)
        const defaultSlot = () => (<div class="w-full flex flex-col">
            {result.value === "" ? <NCard contentStyle={{minWidth: "605px",}}>
                {errorText.value ? <div class="text-center bg-red-400 h-20px">{errorText.value}</div> :
                    <div class="text-center h-20px">{errorText.value}</div>}
                <Flexform ref={formRef} v-model={[formValue.value, "value"]} formList={formList.value}/>
            </NCard> : result.value === "success" ? <NCard contentStyle={{minWidth: "605px",}}>
                <NResult status={'success'} title={'成功'} description={resultText.value} />
            </NCard> : result.value === "failed" ? <NCard contentStyle={{minWidth: "605px",}}>
                <NResult status={'error'} title={'错误'} description={resultText.value} />
            </NCard> : null}
        </div>)
        return () => (<NModal show={showModel.value} onUpdateShow={(val) => showModel.value = val} preset={"dialog"}
                              title={title.value} showIcon={false} loading={loading.value}
                              v-slots={{action: actionSlot, default: defaultSlot,}}>
        </NModal>)
    },
})
